from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from app.core.responses import Response


class ApiException(Exception):
    def __init__(self, message, code: int = 200):
        self.code = code
        self.message = message


# 定义异常方法
def register_exception(app: FastAPI):
    @app.exception_handler(ApiException)
    async def unicorn_exception_handler(request: Request, exc: ApiException):
        return JSONResponse(
            status_code=200,
            content=Response.failed(message=exc.message, code=exc.code).to_dict()
        )
